package internal

import (
	"errors"
	"strings"
)

// 数据库插入修改
func SqlExcute(table string, data map[string]string, where string) (num int64, err error) {
	if table == "" {
		err = errors.New("表名不能为空")
		num = 0
		return
	}
	if data == nil {
		err = errors.New("表名不能为空")
		num = 0
		return
	}
	o := orm.NewOrm()
	sql := ""
	if where == "" {
		var field []string
		var value []string
		for k, v := range data {
			field = append(field, "`"+k+"`")
			if v != "" {
				value = append(value, "'"+v+"'")
			} else {
				value = append(value, "null")
			}
		}
		field_str := strings.Join(field, ",")
		value_str := strings.Join(value, ",")
		sql = "insert into " + table + "(" + field_str + ") values(" + value_str + ")"

	} else {
		var set []string
		for k, v := range data {
			if v != "" {
				set = append(set, "`"+k+"`='"+v+"'")
			} else {
				set = append(set, "`"+k+"`=null")
			}
		}
		set_str := strings.Join(set, ",")
		sql = "update " + table + " set " + set_str + " where " + where

	}
	res, err2 := o.Raw(sql).Exec()
	if err2 != nil {
		err = err2
		num = 0
	} else {
		num, err = res.LastInsertId()
	}
	return
}
